package jpf.nextsearch.ds.manager.impl;

import java.util.Collection;

import jpf.nextsearch.base.GenericObject;
import jpf.nextsearch.ds.dao.ResourceDao;
import jpf.nextsearch.ds.manager.ResourceManager;
import jpf.nextsearch.ds.model.ResourceVO;
import jpf.nextsearch.ds.model.types.ResourceActiveTable;
import jpf.nextsearch.exception.DataAccessException;

public class ResourceManagerImpl extends GenericObject implements ResourceManager {

	private ResourceDao resourceDao;

	@Override
	public void addResources(Collection<ResourceVO> items) throws DataAccessException {
		if (isLoggingDebug()) {
			getLogger().debug(" -> addResources");
		}
		try {
			getResourceDao().saveOrUpdateAll(items);
		} catch (Exception e) {
			if (isLoggingError()) {
				getLogger().error("Error occoured while adding resources to database", e);
			}
			throw new DataAccessException("Error occoured while adding resources to database", e);
		}
	}

	// XXXX musi byc propagation required
	@Override
	public ResourceActiveTable getCurrentResourceActiveTable() throws DataAccessException {
		if (isLoggingDebug()) {
			getLogger().debug(" -> getCurrentResourceActiveTable");
		}		
		try {
			Integer currentIntValue = getGlobalConfiguration().getConfigurationValueInteger(CURRENT_RESOURCE_ACTIVE_TABLE_CONFIG_ENTRY);
			if (currentIntValue == null) {
				currentIntValue = ResourceActiveTable.A.toInt();
				getGlobalConfiguration().setConfigurationValue(CURRENT_RESOURCE_ACTIVE_TABLE_CONFIG_ENTRY, currentIntValue.toString());
			}
			return ResourceActiveTable.fromInt(currentIntValue);
		} catch (Exception e) {
			if (isLoggingError()) {
				getLogger().error("Error occoured while getCurrentResourceActiveTable", e);
			}
			throw new DataAccessException("Error occoured while getCurrentResourceActiveTable", e);
		}
	}

	// XXXX musi byc propagation required
	@Override
	public ResourceActiveTable getNewResourceActiveTable() throws DataAccessException {
		if (isLoggingDebug()) {
			getLogger().debug(" -> getNewResourceActiveTable");
		}			
		ResourceActiveTable current = getCurrentResourceActiveTable();
		if (ResourceActiveTable.A.equals(current)) {
			return ResourceActiveTable.B;
		} else {
			return ResourceActiveTable.A;
		}
	}

	@Override
	public void switchCurrentResourceActiveTable() throws DataAccessException {
		if (isLoggingDebug()) {
			getLogger().debug(" -> switchCurrentResourceActiveTable");
		}			
		ResourceActiveTable current = getCurrentResourceActiveTable();
		ResourceActiveTable neww = null;
		if (ResourceActiveTable.A.equals(current)) {
			neww = ResourceActiveTable.B;
		} else {
			neww = ResourceActiveTable.A;
		}
		getGlobalConfiguration().setConfigurationValue(CURRENT_RESOURCE_ACTIVE_TABLE_CONFIG_ENTRY, Integer.toString(neww.toInt()));
		getResourceDao().removeResourceByActiveTable(current);
	}

	public void setResourceDao(ResourceDao resourceDao) {
		this.resourceDao = resourceDao;
	}

	public ResourceDao getResourceDao() {
		return resourceDao;
	}

}
